//
//  ChangeMessageVC.m
//  HongFuShop
//
//  Created by chirui on 2017/7/31.
//  Copyright © 2017年 Shui. All rights reserved.
//

#import "ChangeMessageVC.h"
#import "UserTypeViewController.h" // 用户等级
#import "DeveloperViewController.h"

@interface ChangeMessageVC ()
<UIPickerViewDataSource, UIPickerViewDelegate>{
    NSString * address;
    NSString * chooseCidStr;
    NSString * areaIdStr;  // 城市选择id
    // 地区选择
    NSInteger _provinceIndex;   // 省份选择 记录
    NSInteger _cityIndex;       // 市选择 记录
    NSUInteger _areaIndex;      // 地区 记录
    
    NSString * provinceIdStr;  //省级代码
    NSString * cityIdStr;     //市级代码
    
    
    NSData * imageData;
    NSString * _chooseType;
    
    NSString * compayId;
    NSString * vipId;
    NSString * classId;
    NSString * shoperId;
    NSString * sellerId;
    NSString * developerId;
    
    NSArray * compayArray;
    NSArray * vipArray;
    NSArray * classArray;
    NSArray * shoperArray;
    NSArray * sellerArray;
    
}
@property (weak, nonatomic) IBOutlet UIScrollView *scrollView;
@property (weak, nonatomic) IBOutlet UIButton *photoBtn;
@property (weak, nonatomic) IBOutlet UITextField *nameText;
@property (weak, nonatomic) IBOutlet UITextField *addressText;
@property (weak, nonatomic) IBOutlet UILabel *compayLabel;
@property (weak, nonatomic) IBOutlet UILabel *vipTypeLabel;
@property (weak, nonatomic) IBOutlet UILabel *userTypeLabel;
@property (weak, nonatomic) IBOutlet UILabel *shopLabel;
@property (weak, nonatomic) IBOutlet UILabel *sellerLabel;
@property (weak, nonatomic) IBOutlet UITextField *areLabel;
@property (nonatomic, strong) UIPickerView * pickerView;
@property (nonatomic, strong) NSArray * arrayDS;
@property (weak, nonatomic) IBOutlet UILabel *newsSeller;

@end

@implementation ChangeMessageVC


- (void)viewDidLoad {
    [super viewDidLoad];
    
    TitleView(@"个人信息");
    
    _chooseType = @"0";
    
    compayId=@"";
    vipId=@"";
    classId = @"";
    shoperId=@"";
    sellerId= @"";
    
    if (self.userDic) {
        
        [_photoBtn sd_setBackgroundImageWithURL:ImageUrl(self.userDic[@"avatar"]) forState:UIControlStateNormal placeholderImage:ImageName(@"img_user_default")];
        
        
        
        _nameText.text = self.userDic[@"user_name"];
        _areLabel.text = self.userDic[@"area"];
        _addressText.text = self.userDic[@"addr"];
        
        NSString * compayStr = self.userDic[@"company_name"];
        NSString * vipStr = self.userDic[@"level_name"];
        NSString * userTypeStr = self.userDic[@"user_sort_dict"];
        NSString * shoperStr = self.userDic[@"dealer_name"];
        NSString * sellerStr = self.userDic[@"seller_name"];
        NSString * developerStr = self.userDic[@"developer_name"];
        
        if (compayStr.length<=0) {
             _compayLabel.text = @"请选择所属公司";
        }else{
            _compayLabel.textColor = [UIColor blackColor];
             _compayLabel.text = compayStr;
        }
        if (vipStr.length<=0) {
            _vipTypeLabel.text = @"请选择用户等级";
        }else{
           _vipTypeLabel.textColor = [UIColor blackColor];
           _vipTypeLabel.text = vipStr;
        }
        if (userTypeStr.length<=0) {
            _userTypeLabel.text = @"请选择用户类别";
        }else{
            _userTypeLabel.textColor = [UIColor blackColor];
            _userTypeLabel.text = userTypeStr;
        }
        if (shoperStr.length<=0) {
            _shopLabel.text = @"请选择上级经销商";
        }else{
            _shopLabel.textColor = [UIColor blackColor];
            _shopLabel.text = shoperStr;
        }
        if (sellerStr.length<=0) {
           
            _newsSeller.text = @"";
        }else{
            _newsSeller.textColor = [UIColor blackColor];
            _newsSeller.text = sellerStr;
        }
        
        if (developerStr.length<=0) {
            
            _sellerLabel.text = @"请选择开发者";
        }else{
            _sellerLabel.textColor = [UIColor blackColor];
            _sellerLabel.text = developerStr;
        }


        compayId=self.userDic[@"company_id"];
        vipId=self.userDic[@"level_id"];
        classId = self.userDic[@"user_sort"];
        shoperId=self.userDic[@"dealer_id"];
        developerId= self.userDic[@"developer_id"];
        
    }
    
    [self getCompayRequest];
    [self getuserRequest];
   
    
    NSString * path = [[NSBundle mainBundle] pathForResource:@"region" ofType:@"json"];
    NSData *fileData = [NSData dataWithContentsOfFile:path];
    
    self.arrayDS = [NSJSONSerialization JSONObjectWithData:fileData options:NSJSONReadingMutableLeaves error:nil];
    
    _scrollView.backgroundColor = [UIColor whiteColor];
    _scrollView.showsVerticalScrollIndicator =NO;
    _scrollView.contentSize = CGSizeMake(WIDTH, 667);
    _scrollView.userInteractionEnabled=YES;
    _scrollView.bounces = YES;
    _scrollView.pagingEnabled = NO;
    
    _photoBtn.layer.cornerRadius = 55/2.f;
    _photoBtn.layer.masksToBounds = YES;
    
    self.navigationItem.leftBarButtonItem = [UIBarButtonItem itemWithIcon:@"icon_public_return" target:self action:@selector(back)];
    self.navigationItem.rightBarButtonItem = [UIBarButtonItem rightItemWithTitle:@"保存" target:self action:@selector(sureBtnClick)];
    
    _areLabel.inputView = self.pickerView;
     
     [_compayLabel tapAction:^{
         
         
         if (compayArray.count>0) {
             
             NSMutableArray * booldArray = [[NSMutableArray alloc]init];
             if (booldArray.count>0) {
                 [booldArray removeAllObjects];
             }
             for (NSDictionary * dic in compayArray) {
                 
                 [booldArray addObject:dic[@"company_name"]];
             }
             
             zySheetPickerView * pickerView = [zySheetPickerView ZYSheetStringPickerWithTitle:booldArray andHeadTitle:@"选择公司" Andcall:^(zySheetPickerView *pickerView, NSString *choiceString) {
                 
                 for (NSDictionary * dic in compayArray) {
                     
                     if ([choiceString isEqualToString:dic[@"company_name"]]) {
                         
                         compayId = dic[@"company_id"];
                     }
                 }
                 
                 [self getShoperRequest];
                 [self getSellerRequest];
                 NSLog(@"compayId=  %@",compayId);
                 _compayLabel.text = choiceString;
                 _compayLabel.textColor = [UIColor blackColor];
                 _shopLabel.text = @"请选择上级经销商";
                 _shopLabel.textColor = [UIColor lightGrayColor];
                 
                 _sellerLabel.text = @"请选择销售员";
                 _sellerLabel.textColor = [UIColor lightGrayColor];
                 
                 [pickerView dismissPicker];
                 
             }];
             [pickerView show];
         }else {
         
             [self getCompayRequest];
         }
        
         
    }];
    
    [_vipTypeLabel tapAction:^{
        
        UserTypeViewController * user =[[UserTypeViewController alloc]init];
        user.block = ^(NSString * messageStr,NSString * chooseIdStr){
        
            _vipTypeLabel.text= messageStr;
            _vipTypeLabel.textColor = [UIColor blackColor];
            
            vipId = chooseIdStr;
        };
        [self.navigationController pushViewController:user animated:YES];
    }];
    [_userTypeLabel tapAction:^{
        
        
        if (classArray.count>0) {
            
            NSMutableArray * booldArray = [[NSMutableArray alloc]init];
            if (booldArray.count>0) {
                [booldArray removeAllObjects];
            }
            for (NSDictionary * dic in classArray) {
                
                [booldArray addObject:dic[@"name"]];
            }
            
        zySheetPickerView * pickerView = [zySheetPickerView ZYSheetStringPickerWithTitle:booldArray andHeadTitle:@"用户类别" Andcall:^(zySheetPickerView *pickerView, NSString *choiceString) {
            
            
            
            for (NSDictionary * dic in classArray) {
                
                if ([choiceString isEqualToString:dic[@"name"]]) {
                    classId = dic[@"value"];
                }
            }
            _userTypeLabel.text = choiceString;
            _userTypeLabel.textColor = [UIColor blackColor];
            [pickerView dismissPicker];
        }];
        [pickerView show];
        }else{
            
            [self getuserRequest];
        }
 
        }];
    [_shopLabel tapAction:^{
        
        if (compayId==nil||_compayLabel.text.length<=0||compayId.length<=0) {
            
            SHuiMBhudTextTimeStr(@"请先选择所属公司");
            
            return;
        }
        
        if (shoperArray.count>0) {
            
            NSMutableArray * booldArray = [[NSMutableArray alloc]init];
            if (booldArray.count>0) {
                [booldArray removeAllObjects];
            }
            for (NSDictionary * dic in shoperArray) {
                
                [booldArray addObject:dic[@"user_name"]];
            }

        zySheetPickerView * pickerView = [zySheetPickerView ZYSheetStringPickerWithTitle:booldArray andHeadTitle:@"上级经销商" Andcall:^(zySheetPickerView *pickerView, NSString *choiceString) {
            
            for (NSDictionary * dic in shoperArray) {
                
                if ([choiceString isEqualToString:dic[@"user_name"]]) {
                    shoperId  = dic[@"dealer_id"];
                }
            }
            
            _shopLabel.text = choiceString;
            _shopLabel.textColor = [UIColor blackColor];
            [pickerView dismissPicker];
            
        }];
        [pickerView show];
            
        }else {
        
            [self getShoperRequest];
        }
    }];
    [_sellerLabel tapAction:^{
        
        
        DeveloperViewController * developer =[[DeveloperViewController alloc]init];
        
        developer.block = ^(NSString * developerName,NSString * developer){
            
            _sellerLabel.text = developerName;
            _sellerLabel.textColor =[UIColor blackColor];
            
            developerId = developer;
        };
        
        [self.navigationController pushViewController:developer animated:YES];
        
        
//        if (compayId==nil||_compayLabel.text.length<=0||compayId.length<=0) {
//            
//            SHuiMBhudTextTimeStr(@"请先选择所属公司");
//            
//            return;
//        }
//        
//        if (sellerArray.count>0) {
//            
//            NSMutableArray * booldArray = [[NSMutableArray alloc]init];
//            if (booldArray.count>0) {
//                [booldArray removeAllObjects];
//            }
//            for (NSDictionary * dic in sellerArray) {
//                
//                [booldArray addObject:dic[@"user_name"]];
//            }
//
//        zySheetPickerView * pickerView = [zySheetPickerView ZYSheetStringPickerWithTitle:booldArray andHeadTitle:@"选择销售员" Andcall:^(zySheetPickerView *pickerView, NSString *choiceString) {
//            
//            for (NSDictionary * dic in sellerArray) {
//                
//                if ([choiceString isEqualToString:dic[@"user_name"]]) {
//                    sellerId  = dic[@"seller_id"];
//                }
//            }
//            
//            _sellerLabel.text = choiceString;
//            _sellerLabel.textColor = [UIColor blackColor];
//            [pickerView dismissPicker];
//            
//        }];
//        [pickerView show];
//        }else{
//            
//            [self getSellerRequest];
//    }
//
        }
     ];
    
}

-(void)back{
    
    [self.navigationController popViewControllerAnimated:YES];
}

-(void)sureBtnClick{
    
    
    if (_nameText.text==nil||_nameText.text.length<=0) {
        
        _nameText.text = @"";
    }
    if (_areLabel.text==nil||_areLabel.text.length<=0) {
        
        _areLabel.text = @"";
    }
    if (_addressText.text==nil||_addressText.text.length<=0) {
        
        _addressText.text = @"";
    }
    if ([_chooseType isEqualToString:@"1"]) {
        
        [self upIconImageRequestFor:imageData];
        
    }else {
    
        [self changeMessageRequest];
    }

}

- (IBAction)photoBtnClick:(id)sender {
    
  
    [_nameText resignFirstResponder];
    [_addressText resignFirstResponder];
    
    [BDImagePicker showImagePickerFromViewController:self allowsEditing:YES finishAction:^(UIImage *image) {
        if (image) {
            
            
            [_photoBtn setBackgroundImage:image forState:UIControlStateNormal];
            
            imageData = UIImageJPEGRepresentation(image, 0.4);
            
            _chooseType = @"1";
            USER_DEFAULTSet(imageData, @"chooseIconImage");
        }
    }];

    
}
-(void)initData
{
    _provinceIndex = _cityIndex =  0;
}


// 懒加载方式
-(UIPickerView *)pickerView

{
    if(!_pickerView){
        
        _pickerView = [[UIPickerView alloc] initWithFrame:CGRectMake(0, HEIGHT - 216, WIDTH, 216)];
        _pickerView.dataSource = self;
        _pickerView.backgroundColor =[UIColor groupTableViewBackgroundColor];
        _pickerView.delegate = self;
        _pickerView.userInteractionEnabled =YES;
        
    }
    return _pickerView;
}

-(void)resetPickerSelectRow
{
    [self.pickerView selectRow:_provinceIndex inComponent:0 animated:YES];
    [self.pickerView selectRow:_cityIndex inComponent:1 animated:YES];
    [self.pickerView selectRow:_areaIndex inComponent:2 animated:YES];
    
}

#pragma mark - PickerView Delegate

// 列数
- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView
{
    return 3;
}

// 每列有多少行
- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component
{
    
    if(component == 0){
        
        
        return self.arrayDS.count;
    }
    else if (component == 1){
        return [self.arrayDS[_provinceIndex][@"sub"] count];
    }else {
        
        return [self.arrayDS[_provinceIndex][@"sub"][_cityIndex][@"sub"] count];
    }
    
}

// 返回每一行的内容
-(NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component
{
    if(component == 0){
        return self.arrayDS[row][@"area"];
    }
    else if (component == 1){
        return self.arrayDS[_provinceIndex][@"sub"][row][@"area"];
    }
    else{
        return self.arrayDS[_provinceIndex][@"sub"][_cityIndex][@"sub"][row][@"area"];
    }
}

// 滑动或点击选择，确认pickerView选中结果
-(void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component
{
    
    if(component == 0){
        _provinceIndex = row;
        _cityIndex = 0;
        _areaIndex = 0;
        [self.pickerView reloadComponent:1];
        [self.pickerView reloadComponent:2];
        
    }
    else if (component == 1){
        _cityIndex = row;
        _areaIndex = 0;
        
        [self.pickerView reloadComponent:2];
    }
    else{
        
        _areaIndex = row;
        
    }
    // 重置当前选中项
    [self resetPickerSelectRow];
    address = [NSString stringWithFormat:@"%@ %@ %@", self.arrayDS[_provinceIndex][@"area"], self.arrayDS[_provinceIndex][@"sub"][_cityIndex][@"area"],self.arrayDS[_provinceIndex][@"sub"][_cityIndex][@"sub"][_areaIndex][@"area"]];
    
    provinceIdStr = self.arrayDS[_provinceIndex][@"area_id"];
    cityIdStr = self.arrayDS[_provinceIndex][@"sub"][_cityIndex][@"area_id"];
    areaIdStr = self.arrayDS[_provinceIndex][@"sub"][_cityIndex][@"sub"][_areaIndex][@"area_id"];
    
    _areLabel.text = address;
    
}


// 只有头像的
-(void)upIconImageRequestFor:(NSData*)data {
    
   
    NSDictionary * dic = @{@"user_id":USER_DEFAULTGet(@"user_id"),
                           @"token":USER_DEFAULTGet(@"token"),
                           @"user_name":_nameText.text,
                           @"area":_areLabel.text,
                           @"addr":_addressText.text,
                           @"company_id":compayId,
                           @"level_id":vipId,
                           @"user_sort":classId,
                           @"dealer_id":shoperId,
                           @"developer_id":developerId
                           };
    
    AFHTTPSessionManager * manager = [AFHTTPSessionManager manager];
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"text/html"];
    SHuiMBhubNoTimeStr(@"正在提交...");
    [manager POST:RequestUrlStr(user_changeMessage_api) parameters:dic constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData){
        
        NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
        formatter.dateFormat = @"yyyyMMddHHmmss";
        NSString *str = [formatter stringFromDate:[NSDate date]];
        NSString *fileName = [NSString stringWithFormat:@"%@.png", str];
        [formData appendPartWithFileData:data name:@"avatar" fileName:fileName mimeType:@"image/png"];
        
    } progress:^(NSProgress * _Nonnull uploadProgress) {
        
        //打印下上传进度
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        SHuiMBHidleYes;
        if ([responseObject[@"code"] intValue]==200) {
            
            
            SHuiMBhudTextTimeStr(@"提交成功");
            
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                
                [self.navigationController popViewControllerAnimated:YES];
            });
            
        }else{
            
            SHuiMBhudTextTimeStr(responseObject[@"mark"]);
        }
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error){
        
        SHuiMBHidleYes;
        
        SHuiMBhudTextTimeStr(@"网络错误，请稍后再试");
        
    } ];
    
}

// 没有图片的
-(void)changeMessageRequest {
    
  
    NSDictionary * dic = @{@"user_id":USER_DEFAULTGet(@"user_id"),
                           @"token":USER_DEFAULTGet(@"token"),
                           @"user_name":_nameText.text,
                           @"area":_areLabel.text,
                           @"addr":_addressText.text,
                           @"company_id":compayId,
                           @"level_id":vipId,
                           @"user_sort":classId,
                           @"dealer_id":shoperId,
                           @"developer_id":developerId
                          };
    
    SHuiMBhubNoTimeStr(@"正在提交...");
    [PostNetWorking postNetWorkingStr:RequestUrlStr(user_changeMessage_api) andparameters:dic Success:^(id responseObject) {
        SHuiMBHidleYes;
        if ([responseObject[@"code"] intValue]== 200) {
            
            SHuiMBhudTextTimeStr(@"提交成功");
            
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                
                [self.navigationController popToRootViewControllerAnimated:YES];
            });
            
        }else{
            
            SHuiMBhudTextTimeStr(responseObject[@"mark"]);
        }
        
    } failed:^(NSError *error) {
        
        SHuiMBHidleYes;
        
        SHuiMBhudTextTimeStr(@"网络错误，请稍后再试");
    }];
    
}

//获取公司列表
-(void)getCompayRequest{

    
    [PostNetWorking postNetWorkingStr:RequestUrlStr(get_compayList_api) andparameters:nil Success:^(id responseObject) {
        SHuiMBHidleYes;
        if ([responseObject[@"code"] intValue]== 200) {
           
            compayArray = responseObject[@"datas"];
            
        }else{
            
            SHuiMBhudTextTimeStr(responseObject[@"mark"]);
        }
        
    } failed:^(NSError *error) {
        
        SHuiMBHidleYes;
        
        SHuiMBhudTextTimeStr(@"网络错误，请稍后再试");
    }];

}

//获取用户类别列表
-(void)getuserRequest{
    
    
    [PostNetWorking postNetWorkingStr:RequestUrlStr(get_userClass_api) andparameters:nil Success:^(id responseObject) {
        SHuiMBHidleYes;
        if ([responseObject[@"code"] intValue]== 200) {
            
            classArray = responseObject[@"datas"];
            
        }else{
            
            SHuiMBhudTextTimeStr(responseObject[@"mark"]);
        }
        
    } failed:^(NSError *error) {
        
        SHuiMBHidleYes;
        
        SHuiMBhudTextTimeStr(@"网络错误，请稍后再试");
    }];
    
}

//获取经销商列表
-(void)getShoperRequest{
    
    NSDictionary * dic = @{@"company_id":compayId};
    [PostNetWorking postNetWorkingStr:RequestUrlStr(get_shoperList_api) andparameters:dic Success:^(id responseObject) {
        SHuiMBHidleYes;
        if ([responseObject[@"code"] intValue]== 200) {
            
            shoperArray = responseObject[@"datas"];
            
        }else{
            
            SHuiMBhudTextTimeStr(responseObject[@"mark"]);
        }
        
    } failed:^(NSError *error) {
        
        SHuiMBHidleYes;
        
        SHuiMBhudTextTimeStr(@"网络错误，请稍后再试");
    }];
    
}

//获取销售员列表
-(void)getSellerRequest{
    
    NSDictionary * dic = @{@"company_id":compayId};
    [PostNetWorking postNetWorkingStr:RequestUrlStr(get_sellerList_api) andparameters:dic Success:^(id responseObject) {
        SHuiMBHidleYes;
        if ([responseObject[@"code"] intValue]== 200) {
            
            sellerArray = responseObject[@"datas"];
            
        }else{
            
            SHuiMBhudTextTimeStr(responseObject[@"mark"]);
        }
        
    } failed:^(NSError *error) {
        
        SHuiMBHidleYes;
        
        SHuiMBhudTextTimeStr(@"网络错误，请稍后再试");
    }];
}


@end
